/**
 * TODO
 *
 * @ClassName: GitProvider
 * @author: changhong
 * @since: 2020/5/15 15:18
 */
package life.changhongdeshijie.community.demo.provider;

import com.alibaba.fastjson.JSON;
import life.changhongdeshijie.community.demo.dto.AccessTokendto;
import life.changhongdeshijie.community.demo.dto.GitUser;
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class GitProvider {
    public String getAccessToken(AccessTokendto accessTokendto){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON.toJSONString(accessTokendto),mediaType );
            Request request = new Request.Builder()
//                    .url("https://gitee.com/oauth/token?grant_type=authorization_code&code="+accessTokendto.getCode()+"&client_id="+accessTokendto.getClient_id()+"&redirect_uri="+accessTokendto.getRedirect_uri()+"&client_secret="+accessTokendto.getClient_secret())
                    .url("https://gitee.com/oauth/token?grant_type=authorization_code&")
                    .post(body)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                String string=response.body().string();
                System.out.println(string);
                String token = string.split(",")[0].split(":")[1].replace("\"","");
//                System.out.println(token);
                return token;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
    }
    public GitUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string=response.body().string();
            GitUser gitUser = JSON.parseObject(string, GitUser.class);
            return gitUser;
        } catch (IOException e) {
        }
        return null;
    }
}
